package com.school.device.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import javax.imageio.ImageIO;

import org.springframework.web.multipart.MultipartFile;

import com.mhuang.school.starter.minio.core.MinioFrame;
import com.school.device.dynamic.AlarmPushUtil;
import com.school.device.dynamic.DvIntellifHikvisonDevice;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CaptureUtil {

	private static String getMD5Digest(String input) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] digest = md.digest(input.getBytes());
			StringBuilder sb = new StringBuilder();
			for (byte b : digest)
				sb.append(String.format("%02x", b));
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Could not find MD5 algorithm", e);
		}
	}

	@SuppressWarnings("unused")
	private static void saveImage(byte[] imageBytes, String filePath) {
		try {
			// 将字节数组转换为输入流
			ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
			// 创建图片
			BufferedImage img = ImageIO.read(bis);
			// 保存图片到指定路径
			ImageIO.write(img, "png", new File(filePath));
			System.out.println("Image saved as " + filePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static String getDate() {
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		return simpleDate.format(new java.util.Date()).replace(" ", "_").replace(":", "-");
	}
	
	private static MultipartFile inputStreamToMultipartFile(InputStream inputStream, String fileName) {
		try {
			return new MockMultipartFile(fileName, fileName, "image/jpeg", inputStream);
		} catch (IOException e) {
			log.error("输入流转文件失败:", e);
		}
		return null;
	}
	
	public static void sendPicurl(String ips,DvIntellifHikvisonDevice device, String pushUrl,MinioFrame minioFrame) {		
		if(device.getDeviceType()==1)
			return;
		CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> dhFireChannelUrl(device, 1, minioFrame));
		CompletableFuture<String> futureB = CompletableFuture.supplyAsync(() -> dhFireChannelUrl(device, 2, minioFrame));
		String picurl = futureA.join();
		String picurl2 = futureB.join();
		AlarmPushUtil.pushMsg(device, picurl, picurl2, pushUrl);
	}

	//channel通道编号
	private static String dhFireChannelUrl (DvIntellifHikvisonDevice device, Integer channel, MinioFrame minioFrame) {

		String ip=device.getDeviceIp();
		String username=device.getAccount();
		String password=device.getPassword();
		String url = "http://"+ip+"/cgi-bin/snapshot.cgi?channel="+channel+"&type=0";
		HttpResponse response = HttpRequest.get(url).execute();
		Map<String, List<String>> headers = response.headers();
		String authenticate = headers.get("WWW-Authenticate").get(0);
		String nonce = authenticate.split("nonce=\"")[1].split("\"")[0];
		String realm = authenticate.split("realm=\"")[1].split("\"")[0];
		// # 生成摘要身份验证的响应值
		String ha1 = getMD5Digest(username + ":" + realm + ":" + password);
		String ha2 = getMD5Digest("GET:" + url);
		String responses = getMD5Digest(ha1 + ":" + nonce + ":00000001:randomstring:auth:" + ha2);
		String headerString = "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce + "\", uri=\"" + url + "\", qop=auth, nc=00000001, cnonce=\"randomstring\", response=\"" + responses + "\"";
		HttpResponse resp = HttpRequest.get(url).header("Authorization", headerString).execute();
		if(resp.isOk()) {
			try (ByteArrayInputStream byteArrInput = new ByteArrayInputStream(resp.bodyBytes())) {
				log.info("获取大华火点图片");
				if (minioFrame == null) {
					System.err.println("minio is null,file:" + getDate() + ".jpg");
					throw new RuntimeException("minio is null,file");
				} else {
					//通道1图片
					MultipartFile multipartFile = inputStreamToMultipartFile(byteArrInput, getDate() + ".jpg");
					String picurl = minioFrame.upload(multipartFile, null);
					log.info("上传文件地址: {}, 通道号{}", picurl, channel);
					return picurl;
				}
			} catch (Exception e) {
				throw new RuntimeException("获取文件流错误 {}", e);
			}
		}else {
			throw new RuntimeException("获取大华火点抓拍图片错误");
		}
	}
		
	//获取序列号   
	public static String getSerialNo(String ip,String username,String password) {		
		String url = "http://"+ip+"/cgi-bin/magicBox.cgi?action=getSerialNo";		
		HttpResponse response = HttpRequest.get(url).execute();
		Map<String, List<String>> headers = response.headers();
		String authenticate = headers.get("WWW-Authenticate").get(0);
		String nonce = authenticate.split("nonce=\"")[1].split("\"")[0];
		String realm = authenticate.split("realm=\"")[1].split("\"")[0];
		// # 生成摘要身份验证的响应值
		String ha1 = getMD5Digest(username + ":" + realm + ":" + password);
		String ha2 = getMD5Digest("GET:" + url);
		String responses = getMD5Digest(ha1 + ":" + nonce + ":00000001:randomstring:auth:" + ha2);
		String headerString = "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce + "\", uri=\"" + url + "\", qop=auth, nc=00000001, cnonce=\"randomstring\", response=\"" + responses + "\"";
		HttpResponse resp = HttpRequest.get(url).header("Authorization", headerString).execute();
		if(resp.isOk()) 
			return resp.body();
		return null;
	}
		
	public static void main(String[] args) {
		//String ss=getPicurl("192.168.0.166","admin","ggmm2016","/SnapShotFilePath/2025-03-03/09/39/666888_99_100_20250303093921232.jpg");
	}
	//获取照片 
	public static InputStream getPicurl(String ip,String username,String password,String picUrl) {			
		String url = "http://" + ip + "/cgi-bin/RPC_Loadfile/" + picUrl;
		HttpResponse response = HttpRequest.get(url).execute();
		Map<String, List<String>> headers = response.headers();
		String authenticate = headers.get("WWW-Authenticate").get(0);
		String nonce = authenticate.split("nonce=\"")[1].split("\"")[0];
		String realm = authenticate.split("realm=\"")[1].split("\"")[0];
		// # 生成摘要身份验证的响应值
		String ha1 = getMD5Digest(username + ":" + realm + ":" + password);
		String ha2 = getMD5Digest("GET:" + url);
		String responses = getMD5Digest(ha1 + ":" + nonce + ":00000001:randomstring:auth:" + ha2);
		String headerString = "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce + "\", uri=\"" + url + "\", qop=auth, nc=00000001, cnonce=\"randomstring\", response=\"" + responses + "\"";
		HttpResponse resp = HttpRequest.get(url).header("Authorization", headerString).execute();
		if(resp.isOk()) 
			return resp.bodyStream();
		return null;
	}
}
